package com.mouse.hxsj.view;

import com.mouse.damo.micro.Com;
import com.mouse.damo.micro.Sleep;
import com.mouse.hxsj.constants.ComPool;
import com.mouse.hxsj.entity.common.Hwnd;
import com.mouse.hxsj.service.SendService;
import com.mouse.hxsj.util.ViewGet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AutoCallFrm extends JInternalFrame {
    private JFormattedTextField textField;
    private JFormattedTextField textField_1;
    private JFormattedTextField textField_2;
    private JTextArea textArea;
    private JComboBox<Hwnd> comboBox;
    private Thread thread;
    private JButton btnNewButton;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AutoCallFrm frame = new AutoCallFrm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public AutoCallFrm() {
        setClosable(true);
        setIconifiable(true);
        setTitle("自动喊话");
        setBounds(20, 20, 570, 300);

        textArea = new JTextArea();
        textArea.setBackground(Color.lightGray);
        JLabel lblNewLabel = new JLabel("句柄");

        comboBox = new JComboBox();

        JLabel lblNewLabel_1 = new JLabel("次数");

        textField = new JFormattedTextField(new java.text.DecimalFormat("#0"));
        textField.setMaximumSize(new java.awt.Dimension(50, 21));
        textField.setMinimumSize(new java.awt.Dimension(50, 21));
        textField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                setNum(textField);
            }
        });
        JLabel lblNewLabel_2 = new JLabel("间隔");

        textField_1 = new JFormattedTextField(new java.text.DecimalFormat("#0"));
        textField_1.setMaximumSize(new java.awt.Dimension(50, 21));
        textField_1.setMinimumSize(new java.awt.Dimension(50, 21));
        textField_1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                setNum(textField_1);
            }
        });
        JLabel lblNewLabel_3 = new JLabel("从");

        btnNewButton = new JButton("开启");
        btnNewButton.addActionListener(e -> {
            start();
        });
        textField_2 = new JFormattedTextField(new java.text.DecimalFormat("#0"));
        textField_2.setColumns(10);
        textField_2.setMaximumSize(new java.awt.Dimension(50, 21));
        textField_2.setMinimumSize(new java.awt.Dimension(50, 21));
        textField_2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                setNum(textField_2);
            }
        });
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                        .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 507, GroupLayout.PREFERRED_SIZE)
                                        .addGroup(groupLayout.createSequentialGroup()
                                                .addComponent(lblNewLabel)
                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 175, GroupLayout.PREFERRED_SIZE)
                                                .addGap(18)
                                                .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
                                                        .addComponent(btnNewButton, Alignment.LEADING)
                                                        .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
                                                                .addGroup(groupLayout.createSequentialGroup()
                                                                        .addComponent(lblNewLabel_1)
                                                                        .addPreferredGap(ComponentPlacement.UNRELATED)
                                                                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE)
                                                                        .addGap(18)
                                                                        .addComponent(lblNewLabel_2)
                                                                        .addPreferredGap(ComponentPlacement.RELATED))
                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                                                .addComponent(lblNewLabel_3)
                                                                .addGap(18)
                                                                .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE)))))
                                .addContainerGap(37, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 144, GroupLayout.PREFERRED_SIZE)
                                .addGap(18)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(lblNewLabel)
                                        .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblNewLabel_1)
                                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblNewLabel_2)
                                        .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblNewLabel_3)
                                        .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addGap(18)
                                .addComponent(btnNewButton)
                                .addContainerGap(36, Short.MAX_VALUE))
        );
        getContentPane().setLayout(groupLayout);

    }

    private void setNum(JFormattedTextField textField) {
        String old = textField.getText();
        JFormattedTextField.AbstractFormatter formatter = textField.getFormatter();
        if (!old.equals("")) {
            if (formatter != null) {
                String str = textField.getText();
                try {
                    long page = (Long) formatter.stringToValue(str);
                    textField.setText(page + "");
                } catch (Exception pe) {
                    textField.setText("0");//解析异常直接将文本框中值设置为0
                }
            }
        }
    }

    private void start() {
        if (thread == null) {
            thread = new Thread(() -> call());
            thread.start();
            btnNewButton.setText("停止");
        } else {
            thread.stop();
            thread = null;
            btnNewButton.setText("开启");
        }


    }

    private void call() {
        String text = textArea.getText();
        String[] split = text.split("\n");
        List<String> list = Arrays.asList(split).stream().filter(s -> !"".equals(s.trim())).collect(Collectors.toList());
        if (list.size() == 0) return;

        Integer times = ViewGet.textField(textField, Integer.class);
        times = times == null || times == 0 ? Integer.MAX_VALUE : times;
        Integer from = ViewGet.textField(textField_1, Integer.class);
        from = from == null || from < 15 ? 15 : from;
        Integer to = ViewGet.textField(textField_2, Integer.class);
        to = to == null || to <= from ? from : to;
        Integer sleepTime = to - from;
        int selectedIndex = comboBox.getSelectedIndex();
        if (selectedIndex < 0) return;
        SendService sendService = new SendService();
        for (int i = 0; i < times; i++) {
            int random1 = (int) (Math.random() * sleepTime) + from;
            int random = (int) (Math.random() * list.size());
            String content = list.get(random);
            System.out.println(content + "-" + times + "-" + from + "-" + to + "-" + selectedIndex + "-" + random1);
            sendService.send(ComPool.getComList().get(selectedIndex), content+i);
            int random2 = (int) (Math.random() * sleepTime) + from;
            Sleep.sleep(random2*1000);
        }
    }

    public void initFrm() {
        List<Com> comList = ComPool.getComList();
        List<String> accountList = ComPool.getAccountList();
        comboBox.removeAllItems();
        for (int i = 0; i < comList.size(); i++) {
            Hwnd hwnd = new Hwnd();
            hwnd.setHwnd(comList.get(i).getHwnd());
            hwnd.setAccount(accountList.get(i));
            comboBox.addItem(hwnd);
        }
    }
}
